// pages/pay/getcoin.js
var config = require('../../config/config'),
	util = require('../../utils/util')

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		userInfo: {},
		coins: 0,
		isAgree: false

	},

	onLoad: function() {
		let userInfo = wx.BaaS.storage.get('userinfo')
		if(userInfo) {
			this.setData({
				userInfo: userInfo
			})

			let coins = wx.BaaS.storage.get('coins')
			if(coins) {
				this.setData({
					coins: coins
				})
			}
		}
	},

	//提交
	formSubmit: function(e) {
		console.log('发龙formID：' + e.detail.formId)

		let that = this,
			data = e.detail.value,
			user_coin = this.data.coins * 1

		let coin_num = data.coin_num * 1

		let postData = {
			coin_num: coin_num,
			uid: wx.BaaS.storage.get('uid') * 1
		}

		postData.formId = e.detail.formId
		wx.BaaS.wxReportTicket(e.detail.formId) //上报formID

		if(this.data.isAgree) {
			//发龙确认
			console.log(postData)
			// 支付示例代码
			let cent = coin_num / 100 * 0.8,
				params = {}
			params.totalCost = cent
			params.merchandiseDescription = '金币兑换' + coin_num + '个,打折后' + cent + '元'

			wx.BaaS.pay(params).then((res) => {
				// success. 支付请求成功响应，可以在 res 中拿到 transaction_no 和支付结果信息

				util.log(2, res.transaction_no, 'GetCoin_' + coin_num) //
				util.changeCoin(postData.uid, coin_num, true, '充值兑换', postData.formId)

				this.setData({
					coins: user_coin + coin_num
				})

				wx.reLaunch({
					url: '../index/index'
				})

			}, (err) => {
				// 未完成用户授权或发生网络异常等
				if(err.code === 603) {
					console.log('用户尚未授权')
				} else if(err.code === 607) {
					console.log('用户取消支付')
				} else if(err.code === 608) {
					console.log(err.message)
				}
			});
		} else {
			util.showToast('请同意自律公约')
		}
	},

	//金币变化
	coinChange: function(e) {
		util.showToast('兑换 ' + e.detail.value + '个金币')
	},

	//是否同意自律公约
	bindAgreeChange: function(e) {
		this.setData({
			isAgree: !!e.detail.value.length
		});
	}

})